<?php
/**
 * 反垃圾识别封装类（主要使用网易易盾服务做支撑）
 * User: lang@vip.deyi.com
 * Date: 2017/6/26
 * Time: 10:49
 */

namespace Deyi\Functions;


use Phalcon\Di;

class SpamDetectFunction
{
    const API_URL = 'https://api.aq.163.com/v3/text/check';

    const API_VERSION = 'v3';

    const API_TIMEOUT = 2;

    private static function genSignature($secretKey, $params)
    {
        ksort($params);
        $buff = "";
        foreach ($params as $key => $value) {
            if ($value !== null) {
                $buff .= $key;
                $buff .= $value;
            }
        }
        $buff .= $secretKey;
        return md5($buff);
    }

    public static function detectText($dataId, $text)
    {
        $config = Di::getDefault()->get('config');

        $params['content'] = UtilFunction::filterUbb($text, true, true, true, true);
        $params['dataId'] = $dataId;

        $params["secretId"] = $config->spam->secretid;
        $params["businessId"] = $config->spam->businessid;
        $params["version"] = self::API_VERSION;
        $params["timestamp"] = sprintf("%d", round(microtime(true) * 1000));// time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int
        $params["signature"] = self::genSignature($config->spam->secretkey, $params);

        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                'method' => 'POST',
                'timeout' => self::API_TIMEOUT, // read timeout in seconds
                'content' => http_build_query($params),
            ),
        );
        $context = stream_context_create($options);
        $result = file_get_contents(self::API_URL, false, $context);
        if ($result === false) {
            return array("code" => 500, "msg" => "file_get_contents failed.");
        } else {
            return json_decode($result, true);
        }
    }

    public static function detectPic()
    {

    }
}